import numpy as np
from src.utils.zaudio import StdRecord
from src.utils.zplot import ZPlot
import RPi.GPIO as GPIO
import time


def SoundSwinger(mode="wave"):
    """使用回调函数的SoundSwinger"""
    sr = StdRecord()
    zp = ZPlot(mode=mode)
    
    def f(data):
        """
        回调函数, 数据处理并显示到OLED上
        """
        data = np.frombuffer(data, dtype=np.int16)  # TODO: 这里int16类型应该根据采样精度而变化
        zp.plot(data)
        
    sr.get_sound_data(f)


open_record = False  # 控制可视化程序的启动和停止
mode = "wave"

def SoundSwinger_wait():
    sr = StdRecord()
    zp = ZPlot(mode=mode)

    key_red = 18
    key_blue = 24

    def key_callback(channel):
        """使用中断方式控制按键"""
        if channel == key_red:
            global open_record
            open_record = not open_record
        elif channel == key_blue:
            global mode
            if mode == "wave":
                mode = "freq"
            else:
                mode = "wave"
            zp.set_mode(mode)
            

    # 控制启动停止的红色按钮
    GPIO.setup(key_red, GPIO.IN, GPIO.PUD_UP)
    GPIO.add_event_detect(key_red, GPIO.FALLING, bouncetime=200)
    GPIO.add_event_callback(key_red, callback=key_callback)

    # 控制模式的蓝色按钮
    GPIO.setup(key_blue, GPIO.IN, GPIO.PUD_UP)
    GPIO.add_event_detect(key_blue, GPIO.FALLING, bouncetime=200)
    GPIO.add_event_callback(key_blue, callback=key_callback)

    while True:
        time.sleep(1)
        if open_record:
            for data in sr.get_sound_data_wait():
                data = np.frombuffer(data, dtype=np.int16)
                zp.plot(data)
                if not open_record:
                    break


def main():
    SoundSwinger_wait()


if __name__ == "__main__":
    main()
    